import React, { Component, useEffect, useRef } from "react";
import { connect } from "dva";
import router from "umi/router";
import { routerRedux } from "dva/router";
import { Card, Button, Icon, Divider, message, Tag } from "antd";
import UserSession from "@/UserSession";
import UploadFile from "./uploadFile";
import styles from './index.less';
import PDFView from './pdfView';
import FileView from './fileView';
import RelatedKnowledgeTag from "@/utils/RelatedKnowledgeTag";
import { getRelKnowledgeTagList, postConnectKnowledgeTag, postFileConfig } from "@/services/knowledgeLabel";

const EditableRow = ({ fileConfig }) => {
	const editorRef = useRef(null);

	useEffect(() => {
		if (editorRef.current) {
			const docEditor = new DocsAPI.DocEditor('placeholder', fileConfig);

			// 你可以添加更多的 ONLYOFFICE 编辑器事件监听器
			// editor.events.on('documentReady', () => console.log('文档已准备好'));
		}
	}, []);

	return <div ref={editorRef} id="placeholder" style={{ width: '100%', height: '600px' }} />;
};

const OnlyOfficeViewer = ({ fileConfig }) => {
	const onlyOfficeContainer = useRef(null);

	useEffect(() => {
		// const script = document.createElement('script');
		// script.src = window.fileUrl + '/web-apps/apps/api/documents/api.js';
		// script.onload = () => {
			const docEditor = new DocsAPI.DocEditor('onlyoffice', fileConfig);
		// };
		// document.body.appendChild(script);
	}, []);

	return <div ref={onlyOfficeContainer} id="onlyoffice" style={{ height: '600px' }} />;
}

import { DocumentEditor } from "@onlyoffice/document-editor-react";

var onDocumentReady = function (event) {
    console.log("Document is loaded");
};

var onLoadComponentError = function (errorCode, errorDescription) {
    switch(errorCode) {
        case -1: // Unknown error loading component
            console.log(errorDescription);
            break;

        case -2: // Error load DocsAPI from http://documentserver/
            console.log(errorDescription);
            break;

        case -3: // DocsAPI is not defined
            console.log(errorDescription);
            break;
    }
};

const EditableApp = ({ fileConfig }) => {
    return (
        <>
            <DocumentEditor
                id="docxEditor"
                documentServerUrl={fileUrl}
                config={fileConfig}
                events_onDocumentReady={onDocumentReady}
                onLoadComponentError={onLoadComponentError}
            />
        </>
    );
}


let timer;
class PreviewFile extends Component {
	constructor(props) {
		super(props);
		this.state = {
			content: '',
			file: null,
			knowledgeTagList: [],
			relatedTagVisible: false,
			pageHeight: 0,
			isPageHeight: false,

			fileConfig: {},
      isAdmin:false
		};
	}

	componentDidMount() {
		const { location: { query ,pathname} } = this.props;
		if (query.fileId) {
			this.info(query.fileId);
			this.getFileConfig(query.fileId);
		};
		timer = setTimeout(() => {
			this.getPageHeight()
		}, 500)
		window.addEventListener('resize', this.getPageHeight)
    this.setState({isAdmin:pathname.indexOf("publicResource") != -1})
	}

	componentWillUnmount() {
		timer && clearTimeout(timer);
		window.removeEventListener('resize', this.getPageHeight)
	}

	getPageHeight = () => {
		console.log(document.getElementById('color_tag_file')?.clientHeight);
		this.setState({ pageHeight: document.getElementById('color_tag_file')?.clientHeight - 76 })
	}

	info = async id => {
		let res = await getRelKnowledgeTagList({ id });
		let knowledgeTagList = [];
		if (res && res.length) {
			res.forEach(item => {
				if (item.tagList && item.tagList.length > 0) {
					item.tagList.forEach(i => {
						knowledgeTagList.push({ color: item.tagColor, id: i.id, name: i.tagValue })
					})
				}
			});
		};
		this.setState({ knowledgeTagList })
	}

	getFileConfig = async id => {
		const { location: { query } } = this.props;
		let res = await postFileConfig({ relId: id, operateType: 2 });
		console.log(res);
		this.setState({ fileConfig: res.fileConfig })
	}

	backRouter = () => {
		this.getKnowledgeFileList();
	}

	getKnowledgeFileList = () => {
		const { match: { params: { id }, }, location: { query }, dispatch,isAdmin } = this.props;
		let pathname = isAdmin ? "/publicResource/documentLibrary/" + id + "/file" : "/documentLibrary/" + id + "/file";
		dispatch(routerRedux.push({ pathname, query: { fileCategoryId: query.fileCategoryId } }));
	}

	updateFile = () => {
		this.uploadFileRef.showModal('UPDATA');
	}

	updateItemFile = (row) => {
		const { location: { params, pathname, query }, dispatch } = this.props;
		// dispatch(routerRedux.push({
		// 	pathname,
		// 	query: { fileCategoryId: query.fileCategoryId, fileId: row.id, fileName: row.docName, fileUrl: row.docPath, previewPath: row.previewPath },
		// }));
		this.backRouter()
	}

	render() {
		const { match: { params: { id }, }, route, location: { params, query } } = this.props;
		const { knowledgeTagList, relatedTagVisible, pageHeight, isPageHeight, fileConfig } = this.state;
		var index = query.fileName.lastIndexOf(".");
		var type = query.fileName?.split('.')?.length > 1 ? query.fileName.split('.')[query.fileName.split('.').length - 1] : '';
		const optionDisabled = query.optionDisabled == 'true' || query.optionDisabled == true ? true : false; 

		return (
			<Card bordered={false}>
				<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', margin: '-8px 0 16px' }}>
					<div style={{ fontWeight: 'bold', fontSize: '15px' }}>
						<span>{query.fileName}</span>
						{/* <Icon type="edit" style={{ marginLeft: 6 }} /> */}
					</div>
					<div>
						
						{UserSession.isSystemKnowledge() ? null : (
							<Button type="primary" style={{ marginRight: 10 }} onClick={() => this.updateFile()} disabled={optionDisabled && optionDisabled == 'true' ? true : false}>更新版本</Button>
						)}
						<Button onClick={this.backRouter} icon="arrow-left">返回</Button>
					</div>
				</div>
				{knowledgeTagList && knowledgeTagList.length > 0 ? (
					<div style={{ marginBottom: 20, display: 'flex', position: 'relative' }}>
						<div style={{ maxHeight: isPageHeight ? 'unset' : '76px', overflow: 'hidden', flex: 1 }}>
							<span id="color_tag_file" style={{ display: 'flex', flexFlow: 'wrap', gap: '12px', }}>
								<span style={{ lineHeight: '32px', fontWeight: 'bold', fontSize: '14px' }}>关联知识标签：</span>
								{knowledgeTagList.map((item, index) => {
									return (
										<>
											{item.color == '#FFF' || item.color == '#FFFFFF' || item.color == '' ? (
												<Tag
													key={index}
													color={item.color}
													style={{
														padding: '5px 12px',
														fontSize: '14px',
														margin: 0,
														color: item.color + '99',
														background: item.color + '1A',
														// border: '1px solid '+ item.color,
													}}
												>
													<span>{item.name}</span>
													<Icon
														type="close"
														style={{
															color: item.color + '99',
															marginLeft: 8,
														}}
														onClick={() => this.removeRelatedTagData(item)}
													/>
												</Tag>
											) : (
												<Tag
													key={index}
													color={item.color}
													style={{
														padding: '5px 12px',
														fontSize: '14px',
														margin: 0,
														color: item.color + '99',
														background: item.color + '1A',
														// border: '1px solid '+ item.color,
													}}
												>
													<span>{item.name}</span>
													<Icon type="close" style={{ color: item.color + '99', marginLeft: 8, }} onClick={() => this.removeRelatedTagData(item)} />
												</Tag>
											)}
										</>
									)
								})}
							</span>
						</div>
						{pageHeight && pageHeight > 0 ? (
							<div style={{ width: '60px' }}>
								<Button type="link" style={{ position: 'absolute', bottom: '0px', right: '0px', }} onClick={() => this.setState({ isPageHeight: !isPageHeight })}>{isPageHeight ? '收起' : '全部'}</Button>
							</div>
						) : null}
					</div>
				) : null}
				<Divider style={{ margin: '0px -24px', width: 'calc(100% + 48px)' }} />

				{/* <div id="placeholder"></div> */}
				{fileConfig && fileConfig != {} && (query.docType == 0 || query.docType == 1 || query.docType == 2 || query.docType == 3) ? (
					<div style={{ height: 'calc(100vh - 180px)', }} className="docxEditor">
						<EditableApp fileConfig={fileConfig} />
					</div>
				) : (
					<div style={{ height: 'calc(100vh - 180px)', overflowY: query.docType == 3 || query.docType == 4 || query.docType == 6 ? 'unset' : 'scroll' }} className={styles.view}>
						{query.docType == 4 ? (
							<iframe class="filename" src={`${window.fileUrl + '/cloud/doc/previewFileByPath?path=' + query.previewPath}#scrollbars=0&toolbar=0&statusbar=0`} width='100%' height='100%' frameborder='0' />
						) : query.docType == 6 ? (
							<iframe class="filename" src={`${window.fileUrl + '/cloud/doc/previewFileByPath?path=' + query.previewPath}#scrollbars=0&toolbar=0&statusbar=0`} width='100%' height='100%' frameborder='0' />
						) : query.docType == 3 ? (
							// <PDFView file={`${window.fileUrl+query.fileUrl}`} />
							// <FileView fileType={type} fileUrl={`${window.fileUrl+query.fileUrl}`} fileState={'unset'} />
							<iframe class="filename" src={`${window.fileUrl + query.previewPath}#scrollbars=0&toolbar=0&statusbar=0`} width='100%' height='100%' frameborder='0' />
						) : (
							<>
								{/* <FileView fileType={'pdf'} fileUrl={`/cloud/doc/previewDoc?fileUrl=${window.fileUrl+query.fileUrl}`} fileState={'unset'} /> */}
								{/* <PDFView file={`/cloud/doc/previewDoc?fileUrl=${window.fileUrl+query.fileUrl}`} /> */}
								<PDFView file={`${window.fileUrl + query.previewPath}`} fileType={type} />
								{/* <iframe class="filename" src={`${window.fileUrl+query.previewPath}#scrollbars=0&toolbar=0&statusbar=0`} width='100%' height='100%' frameborder='0' /> */}
							</>
						)}
					</div>
				)}

				<RelatedKnowledgeTag
					visible={relatedTagVisible}
					onClose={this.closeRelatedTagModal}
					getRelatedList={this.getRelatedTagList}
					onRef={(ref) => (this.RelatedKnowledgeTag = ref)}
				/>
				<UploadFile onRef={ref => this.uploadFileRef = ref} fileId={query.fileId} rootCategoryId={id} updateItemFile={this.updateItemFile} />
			</Card>
		);
	}

	/**
	 * 关联知识标签
	 * @param data
	 * @returns {*}
	 */
	openRelatedKnowledgeTagModal = () => {
		let { knowledgeTagList } = this.state;
		this.RelatedKnowledgeTag.getList(knowledgeTagList);
		this.setState({ relatedTagVisible: true, });
	};

	closeRelatedTagModal = () => {
		this.setState({ relatedTagVisible: false, });
	};

	getRelatedTagList = (data) => {
		this.setState({ knowledgeTagList: data, }, () => {
			this.onRelatedTagSubmit()
		});
	};

	onRelatedTagSubmit = async () => {
		const { location: { query } } = this.props;
		let { knowledgeTagList } = this.state;
		let obj = {
			id: query.fileId,
			knowledgeTagList: knowledgeTagList.map(i => i.id),
		};
		let res = await postConnectKnowledgeTag(obj);
		// console.log(res);
		if (res.code === 0) {
			message.success('操作成功');
		}
	}

	removeRelatedTagData = (tag) => {
		let { knowledgeTagList } = this.state;
		const newData = knowledgeTagList.filter(item => item != tag);
		this.setState({ knowledgeTagList: newData }, () => this.onRelatedTagSubmit());
	};
}

export default connect(({ user }) => ({
	currentUser: user.currentUser,
}))(PreviewFile);
